#!/usr/bin/env python
# coding: utf-8

# In[232]:


# 准备工作
import requests,json
import pandas as pd
from PIL import Image
from io import BytesIO
zhou_key = "a24e04cfaf285a2af77f76b527b2128b"  # 到高德api注册账号申请web服务API类型key


# In[176]:


# 准备起始点和终点
# 数据准备： 
origin = "山东省聊城市东昌府区盛世柳园D区"
destination = "山东省聊城市东昌府区北顺小学"


# In[177]:


# 函数
def geocode(key,address,city=None,batch="false",output="JSON",callback=None)->str:
    """高德API地理编码获取"""
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params_geocode = {
    "key":key,
    "address":address,
    "city":city,
    "batch":batch,
    "output":output,
    "callback":callback
    }
    response = requests.get(url=url_geocode,params=params_geocode)
    results = response.json()['geocodes'][0]['location']  # 列表提取
    
    return results
    


# In[178]:


help(geocode)


# In[179]:


results_起始点 = geocode(zhou_key,origin)
results_起始点


# In[180]:


results_终点 = geocode(zhou_key,destination)
results_终点


# In[181]:


# 逆地理密码的应用
# 1.逆地理编码可以将经纬度转换为详细结构化的地址，且返回附近周边的POI、AOI信息。
# 2.url:https://restapi.amap.com/v3/geocode/regeo?parameters （官网有提供）
# 3.requests.get()
# 4.参数：
# 4.1必选参数：key、location(经纬度坐标)
# 4.2可选参数：
# poitype(返回附近POI类型,需要extensions参数为all时才生效,参数仅支持传入POI TYPECODE，可以传入多个POI TYPECODE，相互之间用“|”分隔。该参数在 batch 取值为true时不生效。获取 POI TYPECODE 可以参考POI分类码表
# radius（搜索半径，取值范围在0~3000，默认是1000。单位：米，缺省值：1000）
# extensions(默认取值是 base，也就是返回基本地址信息；值为 all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息。)
# batch(参数设置为 true 时进行批量查询操作，最多支持 20 个经纬度点进行批量地址查询操作。设置为 false 时进行单点查询，此时即使传入多个经纬度也只返回第一个经纬度的地址解析查询结果。)
# roadlevel（道路等级。当roadlevel=0时，显示所有道路，当roadlevel=1时，过滤非主干道路，仅输出主干道路数据。需要 extensions 参数为 all 时才生效）
# output
# callback
# homeorcorp（供三个可选参数：0：不对召回的排序策略进行干扰。1：综合大数据分析将居家相关的 POI 内容优先返回，即优化返回结果中 pois 字段的poi顺序。2：综合大数据分析将公司相关的 POI 内容优先返回，即优化返回结果中 pois 字段的poi顺序。需要 extensions 参数为 all 时才生效）
# 5.具体应用场景：提供给用户搜索当前所在地周边的生活基础设施，了解当前所在地的繁荣度。


# In[182]:


# 数据准备
address_1 = "山东省聊城市聊城大学" 
city_1 = "山东"
# 每次获取地理编码，只需要在此处填写目标地址和目标地址所在城市（省份）


# In[183]:


# 逆地理密码的获取
"""获取逆地理编码函数"""
"""location为目标地址的坐标"""
def Inverse_geocoding(key,location,poitype=None,radius=1000,extensions='all',batch='false',output='JSON',callback=None,roadlevel=1,homeorcorp=0):
    url = "https://restapi.amap.com/v3/geocode/regeo?parameters"
    params = {
        "key":key,
        "location":location,
        "poitype":poitype,
        "radius":radius,
        "extensions":extensions,
        "batch":batch,
        "output":output,
        "callback":callback,
        "roadlevel":roadlevel,
        "homeorcorp":homeorcorp
}
    response = requests.get(url=url,params=params)
    results = pd.json_normalize(response.json()['regeocode']['pois'])
    return results  # 返回值


# In[184]:


location_聊城大学 = geocode(zhou_key,address_1,city_1)


# In[185]:


Inverse_geocoding(zhou_key,location_聊城大学)


# In[186]:


# 路径规划 准备
# 2.URL
# 2.1步行url:https://restapi.amap.com/v3/direction/walking?parameters
# 2.2公交：https://restapi.amap.com/v3/direction/transit/integrated?parameters
# 2.3驾车：https://restapi.amap.com/v3/direction/driving?parameters
# 3 具体应用场景：帮助用户规划通勤方案。


# In[187]:


# 数据准备(出发地、目的地)
origin_聊城大学 = geocode(zhou_key,address_1,city_1)
destination_北顺小学_1 = "山东省聊城市东昌府区北顺小学"
destination_北顺小学 = geocode(zhou_key,destination_北顺小学_1,city_1)


# In[188]:


"""获取步行路径函数"""
"""origin为起始地的坐标，destination为目的地的坐标"""
def walking(key,origin,destination,output='JSON',callback=None):
    url = "https://restapi.amap.com/v3/direction/walking?parameters"
    params = {
        "key":key,
        "origin":origin,
        "destination":destination,
        "output":output,
        "callback":callback
    }
    response = requests.get(url=url,params=params)
    result = pd.json_normalize(response.json()['route']['paths'][0]['steps'])
    return result


# In[189]:


walking(zhou_key,origin_聊城大学,destination_北顺小学)


# In[190]:


# 公交路径
参数：
必选参数：key、origin（出发地坐标）、destination（目的地坐标）、city（出发地城市）、cityd（目的地城市）


# In[191]:


"""获取公交路径的函数"""
"""origin为起始地的坐标，destination为目的地的坐标,city为出发地城市，cityd为目的地城市"""
def bus(key,origin,destination,city,cityd,extensions='base',strategy=3,nightflag=0,output='JSON',callback=None):
    url = "https://restapi.amap.com/v3/direction/transit/integrated?parameters"
    params = {
        "key":key,
        "origin":origin,
        "destination":destination,
        "city":city,
        "cityd":cityd,
        "extensions":extensions,
        "strategy":strategy,
        "nightflag":nightflag,
        "output":output,
        "callback":callback
    }
    response = requests.get(url,params=params)
    results = response.json()
    return results


# In[192]:


bus(zhou_key,origin_聊城大学,destination_北顺小学,'山东','山东')


# In[193]:


# 步行前往车站路径
pd.json_normalize(bus(zhou_key,origin_聊城大学,destination_北顺小学,'山东','山东')['route']['transits'][0]['segments'][0]['walking']['steps'])


# In[194]:


pd.json_normalize(bus(zhou_key,origin_聊城大学,destination_北顺小学,'山东','山东')['route']['transits'][0]['segments'][0]['bus']['buslines'][0])


# In[195]:


pd.json_normalize(bus(zhou_key,origin_聊城大学,destination_北顺小学,'山东','山东')['route']['transits'][0]['segments'][0]['bus']['buslines'][0]['via_stops'])


# In[196]:


# 驾车路径查询
"""获取驾车路径函数"""
"""origin为起始地的坐标，destination为目的地的坐标"""
"""province为车牌省份汉字缩写，number为车牌处省份外的字母与数字"""
def driving(key,origin,destination,province,number,cartype=0,strategy=10,originid=None,destinationid=None,origintype=None,destinationtype=None,waypoints=None,avoidpolygons=None,avoidroad=None,ferry=0,roadaggregation='false',nosteps=0,output='JSON',callback=None,extensions='base'):
    # 自定义函数名称为driving，括号内为参数。
    url = "https://restapi.amap.com/v3/direction/driving?parameters"
    params = {
        "key":key,
        "origin":origin,
        "destination":destination,
        "originid":originid,
        "destinationid":destinationid,
        "origintype":origintype,
        "destinationtype":destinationtype,
        "strategy":strategy,
        "waypoints":waypoints,
        "avoidpolygons":avoidpolygons,
        "province":province,
        "number":number,
        "cartype":cartype,
        "ferry":ferry,
        "roadaggregation":roadaggregation,
        "nosteps":nosteps,
        "output":output,
        "callback":callback,
        "extensions":extensions
    }
    response = requests.get(url,params=params)
    # 使用normalize函数制作成表格，并提取处我们想要的信息，方便阅读。
    results = pd.json_normalize(response.json()['route']['paths'][0]['steps'])
    return results


# In[197]:


driving_origin = origin_聊城大学
driving_destination = destination_北顺小学
driving_province = "鲁"
driving_number = "577EH"


# In[198]:


driving(zhou_key,driving_origin,driving_destination,driving_province,driving_number)


# In[199]:


# 行政区域查询
 # 1.行政区域查询是一类简单的HTTP接口，根据用户输入的搜索条件可以帮助用户快速的查找特定的行政区域信。
# 2.(url:https://restapi.amap.com/v3/config/district?parameters)
# 3.参数：
# 3.1必选参数：key
# 具体应用场景：帮助用户查询行政区域


# In[200]:


"""查询行政区域函数"""
"""keywords为省市名称"""
def administration(key,keywords,subdistrict=1,page=1,offset=20,extensions="base",output='JSON',callback=None):
    url = "https://restapi.amap.com/v3/config/district?parameters"
    params = {
        "key":key,
        "keywords":keywords,
        "subdistrict":subdistrict,
        "page":page,
        "offset":offset,
        "extensions":extensions,
        "output":output,
        "callback":callback  
    }
    response = requests.get(url,params=params)
    results = pd.json_normalize(response.json()['districts'][0]['districts'])
    return results


# In[201]:


administration_keywords = "山东"


# In[202]:


administration(zhou_key,administration_keywords)


# In[203]:


# 搜索POI
# 关键字搜索
# 具体应用场景：用户可以通过指定区域和指定关键字，搜索到相关的地点的基本信息（图片、位置等）


# In[204]:


"""关键字搜索函数"""
"""keywords为搜索内容的关键字，city为搜索内容所在城市"""
def text(key,keywords,city,types=None,citylimit="true",extensions="all",children=0,offset=20,page=1,output='JSON',callback=None):
    url = "https://restapi.amap.com/v3/place/text?parameters"
    params = {
        "key":key,
        "keywords":keywords,
        "types":types,
        "city":city,
        "citylimit":citylimit,
        "extensions":extensions,
        "children":children,
        "offset":offset,
        "page":page,
        "output":output,
        "callback":callback 
    }
    response = requests.get(url,params=params)
    result = response.json()
    return result


# In[205]:


text_keywords = "旅游景区"
text_city = "山东"


# In[206]:


text(zhou_key,text_keywords,text_city)


# In[207]:


# 周边搜索
# 具体应用场景：用户可以通过关键字和指定中心地点，展开搜索四周的相关内容


# In[208]:


"""周边搜索函数"""
"""location为中心点坐标，keywords为搜索内容关键字"""
def around(key,location,keywords,city=None,radius=3000,sortrule="distance",offset=20,page=1,extensions="base",output='JSON',callback=None):
    url = "https://restapi.amap.com/v3/place/around?parameters"
    params = {
        "key":key,
        "location":location,
        "keywords":keywords,
        "city":city,
        "radius":radius,
        "sortrule":sortrule,
        "offset":offset,
        "page":page,
        "extensions":extensions,
        "output":output,
        "callback":callback 
    }
    response = requests.get(url,params=params)
    result = response.json()
    #result = pd.json_normalize(response.json()['pois'][0]['type'])
    return result


# In[209]:


around_location = origin_聊城大学
around_keywords = "美食"


# In[210]:


around(zhou_key,around_location,around_keywords)


# In[211]:


# ID查询
# 具体应用场景：用户通过兴趣点的唯一标识ID查询到此地点的基本信息（照片、地址等）


# In[212]:


"""ID查询函数"""
"""id为兴趣点的唯一标识ID"""
def id_search(key,id,output='JSON',callback=None):
    url = "https://restapi.amap.com/v3/place/detail?parameters "
    params = {
        "key":key,
        "id":id,
        "output":output,
        "callback":callback 
    }
    response = requests.get(url,params=params)
    result = response.json()
    return result


# In[213]:


id_search(zhou_key,'B00140AKR1')


# In[214]:


# IP定位
# 具体应用场景：通过IP搜索到此IP的相关信息


# In[215]:


"""IP定位函数"""
def ip_locating(key,ip,output='JSON'):
    url = "https://restapi.amap.com/v3/ip?parameters"
    params = {
        "key":key,
        "ip":ip,
        "output":output
    }
    response = requests.get(url,params=params)
    result = response.json()
    return result


# In[216]:


ip_locating(zhou_key,"61.242.54.73")


# In[217]:


# 静态地图
# 具体应用场景：为用户返回指定地点的地图，地图中包括周边路况、基础设施。


# In[218]:


"""获取静态地图函数"""
"""location为中心点坐标，zoom为地图缩放级别:[1,17]"""
def staticmap(key,location,zoom,size="600*300",scale=2,markers=None,labels=None,paths=None,traffic=1):
    #zoom=None,size=400*400,scale=2,markers=None,labels=None,paths=None,traffic=1
    url = "https://restapi.amap.com/v3/staticmap?parameters"
    params = {
        "key":key,
        "location":location,
        "zoom":zoom,
        "size":size,
        "scale":scale,
        "markers":markers,
        "labels":labels,
        "paths":paths,
        "traffic":traffic
    }
    r = requests.get(url,params=params)
    result = r.content
    from PIL import Image
    from io import BytesIO
    i = Image.open(BytesIO(r.content))
    results = i
    return results


# In[219]:


staticmap_location = origin_聊城大学


# In[220]:


staticmap(zhou_key,staticmap_location,17)


# In[221]:


# 坐标转换


# In[222]:


"""坐标转换函数"""
"""location为所需转换的地址的坐标"""
def coordinate_convert(key,locations,coordsys="autonavi",output='JSON'):
    url = "https://restapi.amap.com/v3/assistant/coordinate/convert?parameters"
    params = {
        "key":key,
        "locations":locations,
        "coordsys":coordsys,
        "output":output
    }
    response = requests.get(url,params=params)
    result = response.json()
    return result


# In[223]:


coordinate_convert(zhou_key,origin_聊城大学)


# In[224]:


# 天气查询
# 具体应用场景：为用户返回指定地点的当前天气状况或预测天气状况。


# In[225]:


"""查询天气函数"""
"""city为所需查询的城市的城市编码"""
def weather(key,city,extensions="base",output='JSON'):
    url = "https://restapi.amap.com/v3/weather/weatherInfo?parameters"
    params = {
        "key":key,
        "city":city,
        "extensions":extensions,
        "output":output
    }
    response = requests.get(url,params=params)
    result = pd.json_normalize(response.json()['lives'])
    return result


# In[226]:


weather(zhou_key,"371502")


# In[227]:


# 输入提示
# 具体应用场景：为用户搜索与关键词相关的地点。


# In[228]:


"""获取输入提示函数"""
"""keywords为搜索关键字，city为所需查询的城市的城市编码"""
def inputtips(key,keywords,city,type=None,location=None,citylimit="true",datatype="all",output='JSON',callback=None):
    url = "https://restapi.amap.com/v3/assistant/inputtips?parameters"
    params = {
        "key":key,
        "keywords":keywords,
        "city":city,
        "type":type,
        "location":location,
        "citylimit":citylimit,
        "datatype":datatype,
        "output":output,
        "callback":callback
    }
    response = requests.get(url,params=params)
    result = pd.json_normalize(response.json()['tips'])
    return result


# In[229]:


inputtips(zhou_key,"汽修店","371502")


# In[ ]:





# In[ ]:




